import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Layout,
  Row,
  Col,
  Tree,
  Modal,
  Table,
  Select,
  Input,
  message,
  InputNumber,
  Spin,
  Tag,
  Tooltip,
} from 'antd';
import styles from '@/utils/utils.less';
import PageHeaderWrapper from '@/components/PageHeaderWrapper'; // 引入头部组件
import Authorized from '@/utils/Authorized';
import HOCSelect from '@/components/AntDesign/Select';
import IndexCombina from './IndexCombina';
import IndexDeclaraPolicy from './IndexDeclaraPolicy';
// import IndexCooperativeSupp from './IndexCooperativeSupp';

const { Sider, Content } = Layout;
const { TreeNode } = Tree;
const FormItem = Form.Item;
const { Option } = Select;

@connect(({ localpolicy, loading }) => ({
  localpolicy,
  insDataSource: localpolicy.insDataSource, // 社保组合列表
  accuDataSource: localpolicy.accuDataSource, // 公积金组合列表
  loading: loading.models.localpolicy,
}))
@Form.create()
class BasicList extends PureComponent {
  state = {
    areaLists: [], // 搜索到的城市列表
    policyParamInfo: {}, // 申报政策信息
    treeData: [], // 获取到的左边的城市树
    joinIdeList: [], // 该地区下的缴费人员类别
    fiverisks: '1', // 五险合不合一
    fetching: false, // 搜索的loading
    costCenterList: [], // 该地区下的缴费人员类别
    ADD_DECL_PLCY: [], // 申报政策增员下拉
    DEDU_DECL_PLCY: [], // 申报政策减员下拉
    autoExpandParent: true, // 左侧城市的展开收齐
    addDeclarationPolicy: false, // 控制申报政策修改弹框的显示隐藏
    inputVisible: false, // 控制显示新增缴费人员类别按钮
    inputValue: '', // 新增缴费人员类别名字
    suppliersList: [], // 改地区下的合作供应商
    isDistinguish: 2, // 是否有缴费人员类别
    tempUrl: '', // 查看详情的路由拼接
    addDataSource1: [
      // 无限不合一
      {
        ass: '7',
        assName: '生育',
        plcyPkgMkupPayMth: '',
        plcyPkgAddDeclPlcy: '',
        plcyPkgAddDeclPlcyName: '',
        plcyPkgDeduDeclPlcy: '',
        plcyPkgDeduDeclPlcyName: '',
      },
      {
        ass: '3',
        assName: '养老',
        plcyPkgMkupPayMth: '',
        plcyPkgAddDeclPlcy: '',
        plcyPkgAddDeclPlcyName: '',
        plcyPkgDeduDeclPlcy: '',
        plcyPkgDeduDeclPlcyName: '',
      },
      {
        ass: '6',
        assName: '医疗',
        plcyPkgMkupPayMth: '',
        plcyPkgAddDeclPlcy: '',
        plcyPkgAddDeclPlcyName: '',
        plcyPkgDeduDeclPlcy: '',
        plcyPkgDeduDeclPlcyName: '',
      },
      {
        ass: '5',
        assName: '工伤',
        plcyPkgMkupPayMth: '',
        plcyPkgAddDeclPlcy: '',
        plcyPkgAddDeclPlcyName: '',
        plcyPkgDeduDeclPlcy: '',
        plcyPkgDeduDeclPlcyName: '',
      },
      {
        ass: '4',
        assName: '失业',
        plcyPkgMkupPayMth: '',
        plcyPkgAddDeclPlcy: '',
        plcyPkgAddDeclPlcyName: '',
        plcyPkgDeduDeclPlcy: '',
        plcyPkgDeduDeclPlcyName: '',
      },
      {
        ass: '2',
        assName: '公积金',
        plcyPkgMkupPayMth: '',
        plcyPkgAddDeclPlcy: '',
        plcyPkgAddDeclPlcyName: '',
        plcyPkgDeduDeclPlcy: '',
        plcyPkgDeduDeclPlcyName: '',
      },
    ],
    addDataSource2: [
      // 五险合一
      {
        ass: '3,4,5,6,7',
        assName: '社保',
        plcyPkgMkupPayMth: '',
        plcyPkgAddDeclPlcy: '',
        plcyPkgAddDeclPlcyName: '',
        plcyPkgDeduDeclPlcy: '',
        plcyPkgDeduDeclPlcyName: '',
      },
      {
        ass: '2',
        assName: '公积金',
        plcyPkgMkupPayMth: '',
        plcyPkgAddDeclPlcy: '',
        plcyPkgAddDeclPlcyName: '',
        plcyPkgDeduDeclPlcy: '',
        plcyPkgDeduDeclPlcyName: '',
      },
    ],
  };

  componentDidMount() {
    const { localpolicy, dispatch, insDataSource, accuDataSource, location } = this.props;
    const { pathname } = location;
    const tempUrl = pathname.split('/index')[0];
    this.setState({
      tempUrl,
    });
    // 获取字典
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['ADD_DECL_PLCY', 'DEDU_DECL_PLCY'],
    }).then(res => {
      if (res.ADD_DECL_PLCY && res.DEDU_DECL_PLCY) {
        this.setState({
          ADD_DECL_PLCY: res.ADD_DECL_PLCY,
          DEDU_DECL_PLCY: res.DEDU_DECL_PLCY,
        });
      } else {
        message.warning(res.message || '获取字典错误：服务端未知错误');
        this.setState({
          ADD_DECL_PLCY: [],
          DEDU_DECL_PLCY: [],
        });
      }
    });
    if (localpolicy.areaId === '' && localpolicy.provinceId === '') {
      // 新进来的（ 不是从详情返回回来的 ）
      // 获取合作供应商（ 北京 ）
      this.getCooperSuppList('752252');
      this.getLeftList(); // 获取城市列表
      this.getDeclarationPolicy('752252'); // 获取申报政策信息
      this.paypersonnel('752252'); // 缴费人员类别详情
      this.getInsPkgList('752252', 1, 10); // 获取社保组合列表
      this.getAccuPkgList('752252', 1, 10); // 获取公积金组合列表
    } else {
      this.getCooperSuppList(localpolicy.areaId); // 获取合作供应商
      // 获取该城市下所有的地区
      dispatch({
        type: 'localpolicy/getCityList',
        payload: {
          busiFlag: 1,
        },
      }).then(res => {
        res.data.forEach(item => {
          const temp = item;
          temp.key = temp.areaId;
          temp.title = temp.areaName;
          temp.isLeaf = true;
          temp.cityId = temp.parentId;
          temp.children = [];
        });
        this.setState({
          treeData: res.data,
        });
      });
      // 申报政策详情
      this.getDeclarationPolicy(localpolicy.areaId);
      // 缴费人员类别详情
      this.paypersonnel(localpolicy.areaId);
      // 政策组社保和公积金信息
      this.getInsPkgList(
        localpolicy.areaId,
        insDataSource.pagination.current,
        insDataSource.pagination.pageSize
      );
      this.getAccuPkgList(
        localpolicy.areaId,
        accuDataSource.pagination.current,
        accuDataSource.pagination.pageSize
      );
    }
  }

  // 获取合作供应商的数据
  getCooperSuppList = areaId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'localpolicy/getCooperaSupplier',
      payload: { areaId },
    }).then(res => {
      if (res.success && res.data.length) {
        this.setState({
          suppliersList: res.data,
        });
      } else {
        this.setState({
          suppliersList: [],
        });
      }
    });
  };

  // 获取申报政策信息
  getDeclarationPolicy = areaId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'localpolicy/declarationPolicy',
      payload: { areaId },
    }).then(res => {
      if (res.success) {
        this.setState({
          policyParamInfo: res.data, // 申报政策信息
          isDistinguish: res.data.hshdRegFlag, // 是否区分缴费人员类别
        });
        if (res.data.pkgList) {
          const newAddDataSource = [];
          res.data.pkgList.forEach(pkgitem => {
            newAddDataSource.push({
              ass: pkgitem.ass,
              assName: pkgitem.assName,
              plcyPkgMkupPayMth: pkgitem.plcyPkgMkupPayMth,
              plcyPkgAddDeclPlcy: pkgitem.plcyPkgAddDeclPlcy,
              plcyPkgDeduDeclPlcy: pkgitem.plcyPkgDeduDeclPlcy,
              plcyPkgAddDeclPlcyName: pkgitem.plcyPkgAddDeclPlcyName,
              plcyPkgDeduDeclPlcyName: pkgitem.plcyPkgDeduDeclPlcyName,
            });
          });
          if (String(res.data.insUnifyFlag) === '2') {
            this.setState({
              addDataSource1: newAddDataSource, // 无险不合一
              fiverisks: res.data.insUnifyFlag && res.data.insUnifyFlag.toString(),
            });
          } else {
            this.setState({
              addDataSource2: newAddDataSource, // 无险合一
              fiverisks: res.data.insUnifyFlag && res.data.insUnifyFlag.toString(),
            });
          }
        } else {
          this.setState({
            fiverisks: (res.data.insUnifyFlag && res.data.insUnifyFlag.toString()) || '1',
          });
          this.clearDeclareData();
        }
      } else {
        message.warning(res.message || '服务端未知错误：获取申报政策信息失败');
      }
    });
  };

  // 缴费人员类别详情
  paypersonnel = areaId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'localpolicy/getPaymentPerList',
      payload: { areaId },
    }).then(res => {
      if (res.success) {
        this.setState({
          joinIdeList: res.data,
          costCenterList: res.data,
        });
      } else {
        this.setState({
          joinIdeList: [],
          costCenterList: [],
        });
      }
    });
  };

  // 得到城市列表
  getLeftList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'localpolicy/getCityList',
      payload: {
        busiFlag: 1,
      },
    }).then(res => {
      if (res.success) {
        const newArrSystem = [];
        const tempPro = [];
        const newArr = res.data;
        newArr.forEach(item => {
          const obj = {};
          obj.key = item.areaId;
          obj.title = item.areaName;
          obj.children = [];
          tempPro.push(item.areaId);
          newArrSystem.push(obj);
        });
        this.setState({
          treeData: newArrSystem,
        });
        this.onSelect([newArrSystem[0].key], {});
        if (res.data.length === 1) {
          this.getTreeData(false, { parentId: newArrSystem[0].key }, () => {
            const expandedKeys = [];
            newArrSystem.forEach(item => {
              const temp = item;
              expandedKeys.push(temp.key);
              this.getTreeData(true, { parentId: temp.key }, t => {
                temp.children = t;
              });
            });
            setTimeout(() => {
              this.onExpand(expandedKeys);
            }, 500);
          });
        }
      } else {
        message.warning(res.message);
      }
    });
  };

  // 删除
  handleClose = removedTag => {
    const { costCenterList } = this.state;
    if (costCenterList.length > 0) {
      const newCostCenterList = costCenterList.filter(item => item.ideName !== removedTag);
      this.setState({ costCenterList: newCostCenterList });
    }
  };

  // 点击新增缴费人员类别
  showInput = () => {
    this.setState({ inputVisible: true });
  };

  // 缴费人员类别的值
  handleInputChange = e => {
    this.setState({ inputValue: e.target.value });
  };

  // 缴费人员类别改变的时候
  handleInputConfirm = () => {
    const { inputValue } = this.state;
    let { costCenterList } = this.state;
    if (costCenterList.length > 0) {
      const newCostCenterList = [];
      costCenterList.forEach(item => {
        newCostCenterList.push(item.ideName);
      });
      if (inputValue && newCostCenterList.indexOf(inputValue) === -1) {
        costCenterList = [
          ...costCenterList,
          {
            ideName: inputValue,
          },
        ];
      }
    } else {
      costCenterList = [
        ...costCenterList,
        {
          ideName: inputValue,
        },
      ];
    }
    this.setState({
      costCenterList,
      inputVisible: false,
      inputValue: '',
    });
  };

  // 左侧城市变动时存一下城市id
  onExpand = expandedKeys => {
    this.setState({
      autoExpandParent: false,
    });
    const { dispatch } = this.props;
    const params = {
      city: expandedKeys,
    };
    dispatch({
      type: 'localpolicy/firstStageCity',
      payload: params,
    });
  };

  // 点击新增时候
  addmoney = () => {
    const { localpolicy } = this.props;
    if (localpolicy.areaNames == null) {
      message.warning('请选择城市！');
    } else {
      this.setState({ addDeclarationPolicy: true });
    }
  };

  // 模态框显隐
  handleModalVisible = flag => {
    this.setState({
      addDeclarationPolicy: !!flag,
      isDistinguish: 2,
      costCenterList: [],
    });
    const { localpolicy } = this.props;
    // 缴费人员类别详情
    this.paypersonnel(localpolicy.areaId);
    // 申报政策详情
    this.getDeclarationPolicy(localpolicy.areaId);
  };

  // 子公司get查询
  onLoadData = treeNode => {
    const temp = treeNode;
    const functionId = temp.props.eventKey;
    const { treeData } = this.state;
    return new Promise(resolve => {
      this.getTreeData(true, { parentId: functionId, busiFlag: 1 }, treeDatas => {
        temp.props.dataRef.children = treeDatas;
        this.setState({ treeData: [...treeData] });
      });
      setTimeout(() => {
        resolve();
      }, 500);
    });
  };

  // 申报政策提交
  submitDataList = () => {
    const {
      policyParamInfo,
      addDataSource1,
      addDataSource2,
      costCenterList,
      isDistinguish,
      fiverisks,
      joinIdeList,
    } = this.state;
    const { form, localpolicy, dispatch } = this.props;
    const { areaId, areaNames } = localpolicy;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const data = {
          insUnifyFlag: values.isFiveRisks, // 五险合一标识
          insBeginMth: values.securityyear, // 社保年月起始月
          accuBeginMth: values.providentfund, // 公积金年月起始月
          areaId, // 地区
          areaName: areaNames,
          hshdRegFlag: values.isContributors, // 是否区分缴费人员类别
        };
        if (policyParamInfo.paramId) {
          data.paramId = policyParamInfo.paramId;
          data.vno = policyParamInfo.vno;
        }
        if (String(fiverisks) === '2') {
          data.pkgList = addDataSource1;
        } else {
          data.pkgList = addDataSource2;
        }
        const joinIde = [];
        costCenterList.forEach((items, indexs) => {
          joinIde.push({
            areaId, // 地区
            no: indexs + 1,
            ideName: items.ideName,
            ideId: items.ideId || null,
            vno: items.vno || null,
          });
        });
        if (Number(isDistinguish) === 1) {
          if (costCenterList.length === 0) {
            message.warning('请填写缴费人员类别！');
            return;
          }
        }
        if (Number(values.isContributors) === 1) {
          data.joinIde = joinIde;
        } else {
          data.joinIde = joinIdeList;
        }
        dispatch({
          type: 'localpolicy/submitProMessage',
          payload: data,
        }).then(res => {
          if (res.success) {
            message.success('提交成功！');
            this.setState({
              addDeclarationPolicy: false,
            });
            this.getDeclarationPolicy(areaId); // 申报政策详情
            this.paypersonnel(areaId); // 缴费人员类别详情
          } else {
            message.warning(res.message || '提交失败');
          }
        });
      }
    });
  };

  // 是否区分缴费人员类别
  distinguish = e => {
    this.setState({
      isDistinguish: e,
    });
  };

  // 社保申报五险是否合一
  combination = e => {
    const { form } = this.props;
    form.resetFields();
    this.setState({
      fiverisks: e,
    });
    this.clearDeclareData();
  };

  // 清除申报政策的数据
  clearDeclareData = () => {
    const { addDataSource1, addDataSource2 } = this.state;
    addDataSource1.forEach(item => {
      const temp = item;
      temp.plcyPkgMkupPayMth = '';
      temp.plcyPkgAddDeclPlcy = '';
      temp.plcyPkgAddDeclPlcyName = '';
      temp.plcyPkgDeduDeclPlcy = '';
      temp.plcyPkgDeduDeclPlcyName = '';
    });
    addDataSource2.forEach(items => {
      const temp = items;
      temp.plcyPkgMkupPayMth = '';
      temp.plcyPkgAddDeclPlcy = '';
      temp.plcyPkgAddDeclPlcyName = '';
      temp.plcyPkgDeduDeclPlcy = '';
      temp.plcyPkgDeduDeclPlcyName = '';
    });
    this.setState({
      addDataSource1,
      addDataSource2,
    });
  };

  // 搜索城市
  selectCity = expandedKeys => {
    const { areaLists } = this.state;
    areaLists.forEach(itemcity => {
      if (String(itemcity.areaId) === String(expandedKeys)) {
        if (Number(itemcity.areaNature) === 5 || Number(itemcity.areaNature) === 6) {
          const { dispatch } = this.props;
          const params = {
            provinceId: itemcity.parentId ? itemcity.parentId : null,
            city: itemcity.areaId ? itemcity.areaId : null,
          };
          dispatch({
            type: 'localpolicy/provinceId',
            payload: params,
          });
          const cityIds = [];
          const areaIds = [];
          areaIds.push(itemcity.areaId);
          cityIds.push(itemcity.parentId);
          this.setState({
            autoExpandParent: true,
          });
          const leftparams = {
            city: cityIds,
          };
          const paramers = {
            city: expandedKeys,
          };
          const cityname = {
            cityName: itemcity.areaName,
          };
          dispatch({
            type: 'localpolicy/cityIds',
            payload: cityname,
          });
          dispatch({
            type: 'localpolicy/leftCityids',
            payload: paramers,
          });
          dispatch({
            type: 'localpolicy/firstStageCitys',
            payload: leftparams,
          });
          this.getCooperSuppList(itemcity.areaId); // 获取合作供应商
          this.getDeclarationPolicy(itemcity.areaId); // 申报政策详情
          this.paypersonnel(itemcity.areaId); // 获取缴费人员类别
          this.getInsPkgList(itemcity.areaId, 1, 10);
          this.getAccuPkgList(itemcity.areaId, 1, 10);
        }
      }
    });
  };

  // 获取树形数据
  getTreeData = (isLeaf, params, callback) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'localpolicy/getTreeList',
      payload: params,
    }).then(res => {
      if (res.success && res.data.length) {
        const treeData = [];
        res.data.forEach(item => {
          treeData.push({
            title: item.areaName,
            key: item.areaId,
            cityId: item.parentId,
            dataInfo: item,
            isLeaf: !!(isLeaf || Number(item.functionType) === 1),
          });
        });
        callback(treeData);
      }
    });
  };

  // 城市的子公司
  formatter = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode
            style={{
              margin: '0 0 0 20px',
              width: '160px',
              whiteSpace: 'nowrap',
              cursor: 'pointer',
            }}
            className="childtreeNode"
            title={item.title}
            key={item.key}
            dataRef={item}
          >
            {this.formatter(item.children)}
          </TreeNode>
        );
      }
      return (
        <TreeNode
          className="childtreeNode"
          {...item}
          dataRef={item}
          style={{
            margin: '0 0 0 20px',
            width: '160px',
            whiteSpace: 'nowrap',
            cursor: 'pointer',
          }}
        />
      );
    });

  // 搜索地区
  search = value => {
    const { dispatch } = this.props;
    if (value.trim().length) {
      this.setState({ areaLists: [], fetching: true });
      dispatch({
        type: 'localpolicy/getCityName',
        payload: { areaName: value },
      }).then(res => {
        if (res.success && res.data.length) {
          this.setState({ areaLists: res.data, fetching: false });
        }
      });
    } else {
      this.setState({ areaLists: [], fetching: false });
    }
  };

  // 选择城市的时候
  onSelect = (selectedKeys, info) => {
    const { dispatch, localpolicy, form } = this.props;
    if (selectedKeys.length > 0) {
      let levelLength = null;
      form.resetFields();
      if (info) {
        levelLength = info.node.props.pos.split('-');
      }
      if (levelLength.length === 2) {
        return;
      }
      if (String(localpolicy.levelLength) === '3') {
        if (info) {
          const cityname = {
            cityName: info.node.props.title,
          };
          dispatch({
            type: 'localpolicy/cityIds',
            payload: cityname,
          });
          this.getCooperSuppList(selectedKeys[0]); // 获取合作供应商
          if (info.selectedNodes[0] && info.selectedNodes[0].props) {
            const params = {
              provinceId: info.selectedNodes[0].props.dataRef.dataInfo
                ? info.selectedNodes[0].props.dataRef.dataInfo.parentId
                : info.selectedNodes[0].props.dataRef.areaId,
              city: info.selectedNodes[0].props.dataRef.dataInfo
                ? info.selectedNodes[0].props.dataRef.dataInfo.areaId
                : info.selectedNodes[0].props.dataRef.areaId,
            };
            dispatch({
              type: 'localpolicy/provinceId',
              payload: params,
            });
          } else {
            const params = {
              provinceId: null,
              city: null,
            };
            dispatch({
              type: 'localpolicy/provinceId',
              payload: params,
            });
          }
        }
        // 养老
        this.setState({
          policyParamInfo: {},
        });
        const leftparams = {
          city: selectedKeys,
        };
        dispatch({
          type: 'localpolicy/leftCityid',
          payload: leftparams,
        });
        if (!selectedKeys.length) {
          return;
        }
        const areaId = selectedKeys[0];
        this.setState({
          policyParamInfo: {},
        });
        this.getDeclarationPolicy(areaId); // 获取申报政策
        this.paypersonnel(areaId); // 缴费人员类别详情
        this.getInsPkgList(areaId, 1, 10);
        this.getAccuPkgList(areaId, 1, 10);
      } else {
        const levelLength1 = (info.node.props.pos && info.node.props.pos.split('-')) || '0';
        dispatch({
          type: 'localpolicy/cityLength',
          payload: { length: levelLength1.length },
        });
        if (String(localpolicy.levelLength1) === '3') {
          form.resetFields();
          if (info) {
            const cityname = {
              cityName: info.node.props.title,
            };
            dispatch({
              type: 'localpolicy/cityIds',
              payload: cityname,
            });
            // 获取合作供应商
            this.getCooperSuppList(selectedKeys[0]);
            if (info.selectedNodes[0]) {
              const params = {
                provinceId: info.selectedNodes[0].props.dataRef.dataInfo
                  ? info.selectedNodes[0].props.dataRef.dataInfo.parentId
                  : info.selectedNodes[0].props.dataRef.areaId,
                city: info.selectedNodes[0].props.dataRef.dataInfo
                  ? info.selectedNodes[0].props.dataRef.dataInfo.areaId
                  : info.selectedNodes[0].props.dataRef.areaId,
              };
              dispatch({
                type: 'localpolicy/provinceId',
                payload: params,
              });
            } else {
              const params = {
                provinceId: null,
                city: null,
              };
              dispatch({
                type: 'localpolicy/provinceId',
                payload: params,
              });
            }
          }
          this.setState({
            policyParamInfo: {}, // 养老
          });
          const leftparams = {
            city: selectedKeys,
          };
          dispatch({
            type: 'localpolicy/leftCityid',
            payload: leftparams,
          });
          if (!selectedKeys.length) {
            return;
          }
          const areaId = selectedKeys[0];
          form.resetFields();
          this.getDeclarationPolicy(areaId); // 获取申报政策
          this.paypersonnel(areaId); // 缴费人员类别详情
          this.getInsPkgList(areaId, 1, 10);
          this.getAccuPkgList(areaId, 1, 10);
        }
      }
    }
  };

  // 获取社保列表
  getInsPkgList = (areaId, currentPage, pageSize) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'localpolicy/getInsList',
      payload: {
        areaId,
        pagerArg: {
          currentPage,
          pageSize,
        },
      },
    });
  };

  // 获取公积金组合列表
  getAccuPkgList = (areaId, nowPage, pageNum) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'localpolicy/getAccuList',
      payload: {
        areaId,
        pagerArg: {
          currentPage: nowPage,
          pageSize: pageNum,
        },
      },
    });
  };

  // 可补缴月数
  moneyMth = (text, record) => {
    const { addDataSource1, addDataSource2, fiverisks } = this.state;
    if (String(fiverisks) === '2') {
      addDataSource1.forEach(item => {
        const temp = item;
        if (String(temp.ass) === String(record.ass)) {
          temp.plcyPkgMkupPayMth = text;
        }
      });
      this.setState({
        addDataSource1,
      });
    } else {
      addDataSource2.forEach(item => {
        const temp = item;
        if (String(temp.ass) === String(record.ass)) {
          temp.plcyPkgMkupPayMth = text;
        }
      });
      this.setState({
        addDataSource2,
      });
    }
  };

  // 增员申报
  addDeclaration = (text, record) => {
    const { addDataSource1, addDataSource2, fiverisks } = this.state;
    if (String(fiverisks) === '2') {
      addDataSource1.forEach(item => {
        const tem = item;
        if (String(tem.ass) === String(record.ass)) {
          tem.plcyPkgAddDeclPlcy = text;
        }
      });
      this.setState({
        addDataSource1,
      });
    } else {
      addDataSource2.forEach(item => {
        const temp = item;
        if (String(temp.ass) === String(record.ass)) {
          temp.plcyPkgAddDeclPlcy = text;
        }
      });
      this.setState({
        addDataSource2,
      });
    }
  };

  // 减员申报
  attriDeclaration = (text, record) => {
    const { addDataSource1, addDataSource2, fiverisks } = this.state;
    if (String(fiverisks) === '2') {
      addDataSource1.forEach(item => {
        const temp = item;
        if (String(temp.ass) === String(record.ass)) {
          temp.plcyPkgDeduDeclPlcy = text;
        }
      });
      this.setState({
        addDataSource1,
      });
    } else {
      addDataSource2.forEach(item => {
        const temp = item;
        if (String(temp.ass) === String(record.ass)) {
          temp.plcyPkgDeduDeclPlcy = text;
        }
      });
      this.setState({
        addDataSource2,
      });
    }
  };

  render() {
    const { loading, localpolicy, form, insDataSource, accuDataSource } = this.props;
    const { getFieldDecorator } = form;
    const {
      treeData,
      policyParamInfo,
      costCenterList,
      autoExpandParent,
      addDeclarationPolicy,
      inputVisible,
      inputValue,
      suppliersList,
      areaLists,
      addDataSource1,
      addDataSource2,
      fiverisks,
      isDistinguish,
      fetching,
      ADD_DECL_PLCY,
      DEDU_DECL_PLCY,
      tempUrl,
      joinIdeList,
    } = this.state;
    const { areaId } = localpolicy;
    const perCategoryColumnstwo = [
      {
        title: '险种',
        dataIndex: 'assName',
        align: 'center',
        width: 120,
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      // {
      //   title: '可补缴月数',
      //   width: 130,
      //   align: 'center',
      //   dataIndex: 'plcyPkgMkupPayMth',
      //   onHeaderCell: () => ({
      //     style: {
      //       fontWeight: 'bold',
      //     },
      //   }),
      //   render: (text, record, index) => (
      //     <div>
      //       {String(record.plcyPkgMkupPayMth) === '0' ? (
      //         <FormItem style={{ margin: '0 0 0 0' }}>
      //           {getFieldDecorator(`plcyPkg${index}`, {
      //             rules: [
      //               {
      //                 required: true,
      //                 message: '输入范围0~99的整数',
      //                 pattern: /^[0-9]{0,2}(\.[0-9]{0,0})?$/,
      //               },
      //             ],
      //             initialValue: '0',
      //           })(
      //             <InputNumber
      //               min={0}
      //               max={99}
      //               placeholder="请输入"
      //               onChange={text1 => this.moneyMth(text1, record, index)}
      //             />
      //           )}
      //         </FormItem>
      //       ) : (
      //         <FormItem style={{ margin: '0 0 0 0' }}>
      //           {getFieldDecorator(`plcyPkg${index}`, {
      //             initialValue: record.plcyPkgMkupPayMth || '',
      //             rules: [
      //               {
      //                 required: true,
      //                 message: '输入范围0~99的整数',
      //                 pattern: /^[0-9]{0,2}(\.[0-9]{0,0})?$/,
      //               },
      //             ],
      //           })(
      //             <InputNumber
      //               min={0}
      //               max={99}
      //               placeholder="请输入"
      //               onChange={text1 => this.moneyMth(text1, record, index)}
      //             />
      //           )}
      //         </FormItem>
      //       )}
      //     </div>
      //   ),
      // },
      {
        title: '增员',
        width: 240,
        align: 'center',
        dataIndex: 'plcyPkgAddDeclPlcy',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
        render: (text, record, index) => (
          <FormItem style={{ margin: '0 0 0 0' }}>
            {getFieldDecorator(`plcyPkgAdd${index}`, {
              rules: [{ required: true, message: ' ' }],
              initialValue: record.plcyPkgAddDeclPlcy ? record.plcyPkgAddDeclPlcy.toString() : '',
            })(
              <HOCSelect
                placeholder="请选择"
                onChange={e => this.addDeclaration(e, record, index)}
                style={{ whith: '200px' }}
              >
                {ADD_DECL_PLCY.map(item => (
                  <Option key={item.itemCode}>{item.itemName}</Option>
                ))}
              </HOCSelect>
            )}
          </FormItem>
        ),
      },
      {
        title: '减员',
        width: 240,
        align: 'center',
        dataIndex: 'plcyPkgDeduDeclPlcy',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
        render: (text, record, index) => (
          <FormItem style={{ margin: '0 0 0 0' }}>
            {getFieldDecorator(`plcyPkgDeduDec${index}`, {
              rules: [{ required: true, message: ' ' }],
              initialValue: record.plcyPkgDeduDeclPlcy ? record.plcyPkgDeduDeclPlcy.toString() : '',
            })(
              <HOCSelect
                placeholder="请选择"
                onChange={e => this.attriDeclaration(e, record, index)}
                style={{ whith: '200px' }}
              >
                {DEDU_DECL_PLCY.map(item => (
                  <Option key={item.itemCode}>{item.itemName}</Option>
                ))}
              </HOCSelect>
            )}
          </FormItem>
        ),
      },
    ];
    const formItemstyle = {
      labelCol: { md: { span: 15 } },
      wrapperCol: { md: { span: 9 } },
    };
    const formItemstyleisPercat = {
      labelCol: { md: { span: 18 } },
      wrapperCol: { md: { span: 6 } },
    };
    const hei = window.screen.height;
    return (
      <div className={styles.tablebutton}>
        <Spin spinning={loading}>
          <PageHeaderWrapper />
          <div style={{ margin: '12px 0 0 12px' }}>
            <Layout>
              <div>
                <Sider
                  style={{
                    background: '#fff',
                    width: '230px',
                    height: hei,
                  }}
                >
                  <div
                    className={styles.policysetTrees}
                    style={{ overflowX: 'hidden', height: hei }}
                  >
                    <h4 style={{ lineHeight: '60px', borderBottom: '1px solid #ebebeb' }}>
                      <HOCSelect
                        placeholder="请选择城市"
                        showSearch
                        showArrow={false}
                        filterOption={false}
                        onSearch={this.search}
                        style={{ width: '170px', margin: '0 14px 0 14px' }}
                        onSelect={(value, option) => this.selectCity(value, option, treeData)}
                        notFoundContent={fetching ? <Spin size="small" /> : null}
                      >
                        {areaLists.map(item => (
                          <Option key={item.areaId}>{item.areaName}</Option>
                        ))}
                      </HOCSelect>
                    </h4>
                    {treeData.length ? (
                      <Tree
                        showLine
                        onSelect={(value, option) => this.onSelect(value, option, treeData)}
                        loadData={this.onLoadData}
                        onExpand={this.onExpand}
                        defaultExpandParent={localpolicy.defaultAreaId}
                        selectedKeys={localpolicy.defaultareaIdArr}
                        expandedKeys={localpolicy.expandedKeys}
                        autoExpandParent={autoExpandParent}
                      >
                        {this.formatter(treeData)}
                      </Tree>
                    ) : (
                      <div style={{ textAlign: 'center' }}>
                        <LoadingOutlined /> 加载中
                      </div>
                    )}
                  </div>
                </Sider>
              </div>

              <Content style={{ background: '#fff', margin: '0 0 0 13px' }}>
                <Row>
                  <h3
                    style={{
                      height: '61px',
                      lineHeight: '61px',
                      borderBottom: '1px solid #ebebeb',
                      textIndent: 25,
                      width: '100%',
                    }}
                  >
                    申报政策
                    <Authorized authority="business:joinIde:insertjoinIde" noMatch={null}>
                      <div style={{ float: 'right' }}>
                        {String(fiverisks) === '1' || String(fiverisks) === '2' ? (
                          <a
                            onClick={() => this.addmoney()}
                            style={{
                              fontSize: '14px',
                              marginRight: 25,
                            }}
                          >
                            修改
                          </a>
                        ) : (
                          <a
                            onClick={() => this.addmoney()}
                            style={{
                              fontSize: '14px',
                              marginRight: 25,
                            }}
                          >
                            新增
                          </a>
                        )}
                      </div>
                    </Authorized>
                  </h3>
                  <IndexDeclaraPolicy
                    suppliersList={suppliersList}
                    addDeclarationPolicy={addDeclarationPolicy}
                    areaNames={localpolicy.areaNames}
                    fiverisks={fiverisks}
                    policyParamInfo={policyParamInfo}
                    costCenterList={costCenterList}
                    addDataSource1={addDataSource1}
                    addDataSource2={addDataSource2}
                  />
                </Row>
                {/* <Row style={{ marginTop: 20 }}>
                  <h3
                    style={{
                      lineHeight: '61px',
                      height: '61px',
                      borderBottom: '1px solid #ebebeb',
                      textIndent: 25,
                      width: '100%',
                    }}
                  >
                    合作供应商
                  </h3>
                  <Form layout="vertical" style={{ margin: '0 30px 0 25px', width: '100%' }}>
                    {suppliersList.length > 0 ? (
                      <IndexCooperativeSupp
                        suppliersList={suppliersList}
                        addDeclarationPolicy={addDeclarationPolicy}
                      />
                    ) : (
                      <div style={{ width: '100px', height: '50px' }}>暂无数据</div>
                    )}
                  </Form>
                </Row> */}
                <Row style={{ marginTop: 20 }}>
                  <h3
                    style={{
                      lineHeight: '61px',
                      height: '61px',
                      borderBottom: '1px solid #ebebeb',
                      textIndent: 25,
                      width: '100%',
                    }}
                  >
                    政策组合信息
                  </h3>
                </Row>
                <Row style={{ margin: '10px  25px' }}>
                  <Col span={24} offset={0}>
                    <IndexCombina
                      tab={localpolicy.tabid}
                      insDataSource={insDataSource}
                      accuDataSource={accuDataSource}
                      areaId={areaId}
                      tempUrl={tempUrl}
                      joinIdeList={joinIdeList}
                    />
                  </Col>
                </Row>
              </Content>
            </Layout>
            <Modal
              width={900}
              title={
                <div>
                  <span style={{ fontSize: '16px' }}>申报政策 </span>
                  <span style={{ fontSize: '14px', color: '#595959' }}>
                    ( {localpolicy.areaNames} )
                  </span>
                </div>
              }
              visible={addDeclarationPolicy}
              okText="保存"
              cancelText="取消"
              destroyOnClose="false"
              onOk={this.submitDataList}
              onCancel={() => this.handleModalVisible(false)}
            >
              <Form>
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                  <Col md={8} sm={24}>
                    <FormItem label="是否五险合一申报" {...formItemstyle}>
                      {getFieldDecorator('isFiveRisks', {
                        rules: [{ required: true, message: '请输入' }],
                        initialValue: fiverisks,
                      })(
                        <HOCSelect
                          onChange={this.combination}
                          placeholder="请选择"
                          style={{ width: '90px' }}
                        >
                          <Option value="1">是</Option>
                          <Option value="2">否</Option>
                        </HOCSelect>
                      )}
                    </FormItem>
                  </Col>
                  <Col md={8} sm={24}>
                    <FormItem label="社保年度起始月：" {...formItemstyle}>
                      {getFieldDecorator('securityyear', {
                        rules: [
                          {
                            required: false,
                            message: '输入范围1~12的整数',
                            pattern: /^[0-9]{0,2}(\.[0-9]{0,0})?$/,
                          },
                        ],
                        initialValue: policyParamInfo.insBeginMth,
                      })(
                        <InputNumber
                          placeholder="请输入"
                          style={{ width: '90px' }}
                          min={1}
                          max={12}
                        />
                      )}
                    </FormItem>
                  </Col>
                  <Col md={8} sm={24}>
                    <FormItem label="公积金年度起始月：" {...formItemstyle}>
                      {getFieldDecorator('providentfund', {
                        rules: [
                          {
                            required: false,
                            message: '输入范围1~12的整数',
                            pattern: /^[0-9]{0,2}(\.[0-9]{0,0})?$/,
                          },
                        ],
                        initialValue: policyParamInfo.accuBeginMth,
                      })(
                        <InputNumber
                          placeholder="请输入"
                          min={1}
                          max={12}
                          style={{ width: '90px' }}
                        />
                      )}
                    </FormItem>
                  </Col>
                </Row>
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                  <Col md={8} sm={24}>
                    <FormItem label="是否区分缴费人员类别" {...formItemstyleisPercat}>
                      {getFieldDecorator('isContributors', {
                        rules: [{ required: true, message: '请输入' }],
                        initialValue: policyParamInfo.hshdRegFlag,
                      })(
                        <HOCSelect
                          placeholder="请选择"
                          style={{ width: '90px' }}
                          onChange={this.distinguish}
                        >
                          <Option value={1}>是</Option>
                          <Option value={2}>否</Option>
                        </HOCSelect>
                      )}
                    </FormItem>
                  </Col>
                  <Col md={16} sm={24}>
                    {Number(isDistinguish) === 1 ? (
                      <div>
                        <Row>
                          <Col
                            style={{
                              float: 'left',
                              margin: '8px 0 15px 45px',
                              color: '#000',
                              width: '23%',
                            }}
                          >
                            <span style={{ color: 'red' }}>* </span>
                            缴费人员类别：
                          </Col>
                          <Col style={{ float: 'left', width: '65%' }}>
                            {costCenterList.map((tagitem, index) => {
                              const isLongTag = tagitem.length > 20;
                              const tagElem = (
                                <Tag
                                  style={{ float: 'left', margin: '8px 0 15px 8px' }}
                                  key={tagitem.ideName}
                                  closable={index !== -1}
                                  onClose={() => this.handleClose(tagitem.ideName, tagitem)}
                                >
                                  {tagitem.ideName}
                                </Tag>
                              );
                              return isLongTag ? (
                                <Tooltip
                                  title={tagitem.ideName}
                                  key={tagitem.ideName}
                                  style={{ float: 'left', margin: '8px 0 15px 8px' }}
                                >
                                  {tagElem}
                                </Tooltip>
                              ) : (
                                tagElem
                              );
                            })}
                            {inputVisible && (
                              <Input
                                type="text"
                                size="small"
                                style={{ width: 78, float: 'left', margin: '8px 0 15px 8px' }}
                                value={inputValue}
                                onChange={this.handleInputChange}
                                onBlur={this.handleInputConfirm}
                                onPressEnter={this.handleInputConfirm}
                              />
                            )}
                            {!inputVisible && (
                              <Tag
                                onClick={this.showInput}
                                style={{
                                  background: '#fff',
                                  borderStyle: 'dashed',
                                  float: 'left',
                                  margin: '8px 0 15px 8px',
                                }}
                              >
                                <PlusOutlined /> 新增
                              </Tag>
                            )}
                            <div style={{ clear: 'both' }} />
                          </Col>
                        </Row>
                      </div>
                    ) : null}
                  </Col>
                </Row>
                <Table
                  dataSource={String(fiverisks) === '2' ? addDataSource1 : addDataSource2}
                  bordered
                  columns={perCategoryColumnstwo}
                  pagination={false}
                  size="default"
                />
              </Form>
            </Modal>
          </div>
        </Spin>
      </div>
    );
  }
}

const BasicListFrom = Form.create()(BasicList);
export default BasicListFrom;
